#!/usr/bin/perl

#BEGIN { $ENV{DEBUG_CB} = 1; }
#BEGIN { $ENV{PERL_DEBUG_MSTATS} = 2; }

use strict;
#use Devel::Leak;
#use Devel::Cycle;
#use Devel::Leak::Object qw{ GLOBAL_bless };
#$Devel::Leak::Object::TRACKSOURCELINES = 1;
use Devel::Leak::Cb;

use Data::Dumper;
use AnyEvent::Twitter::Stream;
$AnyEvent::Twitter::Stream::STREAMING_SERVER = 'localhost:33008';

$|++;
my $g;
my $handle;
my $co;
our $done;
our $guard;

#warn Devel::Leak::NoteSV($handle);

while($co++<9){
$done = AnyEvent->condvar;
$guard = AnyEvent::Twitter::Stream->new(
	username => $ARGV[0],
	password => $ARGV[1],
	method   => "filter",
	track    => "Perl,Test,Music",
	(on_tweet => cb {
		my $tweet = shift;
		print ".";
		warn "\n$tweet->{user}{screen_name}: $tweet->{text}\n";
	}),
	(on_keepalive => cb {
		warn Dumper(@_);
		warn "ping\n";
	}),
	(on_error => cb {
		warn Dumper(@_);
		$guard && $guard->{guard} && $guard->{guard}->cancel;
#		undef $guard;
	#	$co++>999 && exit();
#		$g = set_guard();
		$done->send;
#		warn Devel::Leak::NoteSV($handle);
#		warn Devel::Leak::CheckSV($handle);
	}),
	timeout => 3,
);

#warn Devel::Leak::NoteSV($handle);
$done->recv;
#find_cycle($done);
#find_cycle($guard);
#warn $guard;
#warn Devel::Leak::CheckSV($handle);
}

END {
#warn Devel::Leak::CheckSV($handle);
}
